package com.example.carrierapp.ui.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.carrierapp.bean.home.BannerBean;
import com.example.carrierapp.util.GlideApp;
import com.example.lb.fingerdemo.R;

import java.util.ArrayList;
import java.util.List;


/**
 * 首页广告栏适配器
 */
public class BannerAdapter extends PagerAdapter {
    private final String TAG = "BannerAdapter";
    private Context context;
    private List<BannerBean.ResultBean> listADbeans = new ArrayList<>();

    public BannerAdapter(Context context, List<BannerBean.ResultBean> adBeans) {
        this.context = context;
        listADbeans = setListADbeans(adBeans);
    }

    private List<BannerBean.ResultBean> setListADbeans(List<BannerBean.ResultBean> adBeans) {
        Log.i(TAG, "广告长度 初始长度：" + listADbeans.size());
        if (adBeans.size() > 1) {
            //把广告的最后一个数据添加为列表的第一个
            listADbeans.add(adBeans.get(adBeans.size()-1));
            //遍历广告数据添加进列表
            for (BannerBean.ResultBean adBean : adBeans) {
                listADbeans.add(adBean);
            }
            //把广告的第一个数据添加为列表的最后一个
            listADbeans.add(adBeans.get(0));
            Log.i(TAG, "广告长度 最后长度：" + listADbeans.size());
            return listADbeans;
        } else {
            return adBeans;
        }
    }

    @Override
    public int getCount() {
        return listADbeans.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        //新建一个ImageView用来显示广告
        ImageView imageView = new ImageView(context);
        //设置广告图片
        if (listADbeans.size() == 1) {
            getImage(imageView, 0);
        } else {
            getImage(imageView, position);
            //缓存优化ImageView
            ViewGroup parent = (ViewGroup) imageView.getParent();
            if (parent != null) {
                container.removeView(imageView); //此时parent是container
            }
        }
        //设置图片大小
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        //添加到容器
        container.addView(imageView);

        return imageView;
    }

    private void getImage(final ImageView imageView, int position) {
        GlideApp.with(imageView).load(listADbeans.get(position).getBannerPath()).placeholder(R.mipmap.icon_default_img).into(imageView);
    }
}

